var express = require('express');
var router = express.Router();

//加载mysql数据库
let mysql = require("mysql");
//配置mysql数据库
let config = {
  host: "localhost", 
  port: 3306, 
  user: "root", 
  password: "root", 
  database: "student", 
}

//连接数据库
let connection = mysql.createConnection(config);

//判断是否连接成功
connection.connect((err) => {
  if (err) {
    console.log("连接数据库失败")
  } else {
    console.log("数据库连接成功")
  }
})

//加载验证码包
let svgcaptcha = require("svg-captcha");

//时间戳
let time = require("time-stamp")

//加载fs模块
let fs = require("fs");
//加载path模块
let path = require("path");

//加载解析文件域包
let formidable = require("formidable");

// /* GET users listing. */
// router.get('/', function (req, res, next) {
//   res.send('respond with a resource');
// });

//规划登录路由 渲染登录页面
router.get("/login", (req, res) => {
  let sql = `select username,password from member`;
  connection.query(sql, (err, doc) => {
    if (err) {
      console.log("查询失败")
    } else {
      let msgs = doc;
      res.cookie("mes", msgs);
      res.render("pages/loginAndRegister/login.html", {
        doc: doc
      });
    }
  })
})

//规划路由 加载验证码
router.get("/svgcode", (req, res) => {
  //生成验证码
  let captcha = svgcaptcha.create();
  //将图片中验证码数据存储到cookie中
  res.cookie("code", captcha.text);
  //使用svg生成验证码图片
  res.type("svg");
  //验证码发送给前端
  res.send(captcha.data);
})

//规划登录路由 渲染注册页面
router.get("/register", (req, res) => {
  let sql = `select username,password from member`;
  connection.query(sql, (err, doc) => {
    if (err) {
      console.log("查询失败")
    } else {
      res.render("pages/loginAndRegister/register.html", {
        doc: doc
      });
    }
  })
})


//登录表单数据提交
router.post("/login", (req, res) => {
  let {
    tel,
    pass,
    code
  } = req.body;
  let u = req.cookies.mes.find((item) => {
    return item.username == tel && item.password == pass && req.cookies.code.toUpperCase() == code.toUpperCase();
  });
  if (u) {
    res.send("登录成功")
  } else {
    res.send("用户名或者密码或者验证码错误")
  }
})


//注册表单数据提交
router.post("/register", (req, res) => {
  let {
    tel,
    pass
  } = req.body;
  let u = req.cookies.mes.findIndex((item) => {
    return item.username == tel;
  });
  if (u == -1) {
    let sql = `insert into member (username,password) value ("${tel}","${pass}")`;
    connection.query(sql, (err) => {
      if (err) {
        res.send("添加失败")
      } else {
        res.send("注册成功")
      }
    })
  } else {
    res.send("该用户名已被占用")
  }
})



module.exports = router;